package com.forlove.app.qselect.index.ui;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.widget.recyview.BaseRecyclerAdapter;
import com.forlove.app.manager.FriendManager;
import com.forlove.app.manager.async.LoadContactsAsync;
import com.forlove.app.qselect.CommonEntity;
import com.forlove.app.qselect.friend.entity.ContactsFriendEntity;
import com.forlove.app.qselect.friend.entity.MineFriendEntity;
import com.forlove.app.qselect.friend.ui.AddFriendGuideActivity;
import com.forlove.app.qselect.index.adapter.AddFriendsAdapter;
import com.forlove.app.qselect.index.presenter.AddFriendsPresenter;
import com.forlove.app.qselect.index.view.AddFriendsView;
import com.forlove.app.qselect.login.entity.ContactsInfoEntity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/**
 * 该页面只会首次注册并授权通讯录进入
 * Created by yinzhiqiang on 2017/11/6.
 */

@RuntimePermissions
public class AddFriendsActivity extends BaseActivity<AddFriendsPresenter> implements AddFriendsView,
        LoaderManager.LoaderCallbacks<List<ContactsInfoEntity>>, View.OnClickListener {

    public static final int from_skip = 1;
    public static final int from_next_step = 2;
    @BindView(R.id.recycler_add_friends)
    RecyclerView recyFriends;

    @BindView(R.id.choose_friends)
    TextView chooseFriends;

    @BindView(R.id.ll_btn)
    LinearLayout llBtn;

    @BindView(R.id.iv_icon)
    ImageView btIcon;

    @BindView(R.id.text_skip)
    TextView text_skip;//跳过
    private AddFriendsAdapter addFriendsAdapter;
    private List<ContactsInfoEntity> contactsInfoEntities = new ArrayList<>();//获取通讯录好友
    private List<MineFriendEntity> mergeFriendEntities = new ArrayList<>();//合并好友
    private LoadContactsAsync loadContactsAsync;
    private List<MineFriendEntity> selectFriend = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_friend;
    }

    @Override
    public void initView() {
        if (presenter == null) {
            presenter = new AddFriendsPresenter(this);
        }
        AddFriendsActivityPermissionsDispatcher.needContactsWithPermissionCheck(this);
        initData();
        setCanBack(false);
    }

    private LoadContactsAsync createContacts() {
        if (loadContactsAsync == null) {
            WeakReference<Context> contextWeakReference = new WeakReference<Context>(this);
            loadContactsAsync = new LoadContactsAsync(contextWeakReference.get());
        }
        return loadContactsAsync;
    }

    public void initData() {
        text_skip.setOnClickListener(this);
        addFriendsAdapter = new AddFriendsAdapter(this, R.layout.item_add_friends, mergeFriendEntities, presenter);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        recyFriends.setLayoutManager(gridLayoutManager);
        recyFriends.setAdapter(addFriendsAdapter);
        addFriendsAdapter.hideFooterView();
        addFriendsAdapter.hideEmptyView();
        addFriendsAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                MineFriendEntity mineFriendEntity = mergeFriendEntities.get(position);
                if (mineFriendEntity.isRecomend) {
                    mineFriendEntity.isRecomend = false;
                    selectFriend.remove(mineFriendEntity);
                } else {
                    mineFriendEntity.isRecomend = true;
                    selectFriend.add(mineFriendEntity);
                }
                addFriendsAdapter.notifyItemChanged(position);
                if (selectFriend.size() >= 4) {
                    changeNextButtonStep();
                } else {
                    hideNextButtonStep();
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    private void changeNextButtonStep() {
        llBtn.setBackground(getResources().getDrawable(R.drawable.bt_nextstep_selector));
        chooseFriends.setText("下一步");
        btIcon.setVisibility(View.INVISIBLE);
        llBtn.setOnClickListener(this);
    }

    private void hideNextButtonStep() {
        llBtn.setBackground(getResources().getDrawable(R.drawable.bg_add_friend_btn));
        chooseFriends.setText("至少再选择" + (4 - selectFriend.size()) + "好友");
        btIcon.setVisibility(View.VISIBLE);
        llBtn.setOnClickListener(null);
    }

    @NeedsPermission(Manifest.permission.READ_CONTACTS)
    void needContacts() {
        getSupportLoaderManager().restartLoader(LoadContactsAsync.ASYNC_ID, null, this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getSupportLoaderManager().destroyLoader(LoadContactsAsync.ASYNC_ID);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AddFriendsActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnPermissionDenied(Manifest.permission.READ_CONTACTS)
    void getContactsFail() {
//        presenter.loadContactFriend();
        Toast.makeText(this, "通讯录权限被拒绝", Toast.LENGTH_SHORT).show();
        //获取通讯录号码
//        List<ContactsInfoEntity> contacts = ContactsManager.getContectInfo(this);
//        if (contacts.size() > 0) {
//            contactsInfoEntities.clear();
//            contactsInfoEntities.addAll(contacts);
//        }
    }

    @OnNeverAskAgain(Manifest.permission.READ_CONTACTS)
    void refuseContacts() {
//        presenter.loadContactFriend();
        Toast.makeText(this, "通讯录权限被拒绝", Toast.LENGTH_SHORT).show();
//        //获取通讯录号码
//        List<ContactsInfoEntity> contacts = ContactsManager.getContectInfo(this);
//        if (contacts.size() > 0) {
//            contactsInfoEntities.clear();
//            contactsInfoEntities.addAll(contacts);
//        }
    }

    @Override
    public Loader<List<ContactsInfoEntity>> onCreateLoader(int id, Bundle args) {
        return createContacts();
    }

    @Override
    public void onLoadFinished(Loader<List<ContactsInfoEntity>> loader, List<ContactsInfoEntity> data) {
        getSupportLoaderManager().destroyLoader(LoadContactsAsync.ASYNC_ID);
        //获取完通讯录后再拉数据
        presenter.loadContactFriend();
        if (data != null && data.size() > 0) {
            contactsInfoEntities.clear();
            contactsInfoEntities.addAll(data);
        }
    }

    @Override
    public void onLoaderReset(Loader<List<ContactsInfoEntity>> loader) {
        getSupportLoaderManager().destroyLoader(LoadContactsAsync.ASYNC_ID);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_btn:
                presenter.requestAddFriends(selectFriend);
                break;
            case R.id.text_skip:
                Bundle bundle = new Bundle();
                bundle.putInt("from", from_skip);
                Intent intent = new Intent(this, AddFriendGuideActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
                finish();
                break;
        }
    }

    @Override
    public void updateFriendListView(ContactsFriendEntity friendListEntity) {
        //获取 注册的通讯录好友
        List<MineFriendEntity> mineFriendEntities =
                FriendManager.friendToContacts(friendListEntity.concats, contactsInfoEntities);
        mergeFriendEntities.clear();
        mergeFriendEntities.addAll(mineFriendEntities);
        addFriendsAdapter.updateDatas(mergeFriendEntities);
    }

    @Override
    public void updateAddFriendView(CommonEntity commonEntity) {
        //更新添加好友
        Toast.makeText(this, "设置成功！", Toast.LENGTH_SHORT).show();
//        Bundle bundle = new Bundle();
//        bundle.putInt(MainActivity.Key_Comefrom, MainActivity.COME_FROM_REGISTER);
//        toMainActivity(bundle);

        Bundle bundle = new Bundle();
        bundle.putInt("from", from_next_step);
        bundle.putInt("friendnum", selectFriend.size());
        Intent intent = new Intent(this, AddFriendGuideActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
        finish();
    }
}
